package com.atguigu.tingshu.album.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.cache.TsCache;
import com.atguigu.tingshu.model.album.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@SuppressWarnings({"all"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

	@Autowired
	private BaseCategory1Mapper baseCategory1Mapper;

	@Autowired
	private BaseCategory2Mapper baseCategory2Mapper;

	@Autowired
	private BaseCategory3Mapper baseCategory3Mapper;


	@Autowired
	private BaseCategoryViewMapper baseCategoryViewMapper;

	@Autowired
	private BaseAttributeMapper baseAttributeMapper;

	@Override
	public List<JSONObject> getBaseCategoryList() {
		//	创建集合对象
		List<JSONObject> list = new ArrayList<>();
		//数据来源于数据库
		//使用视图获取数据
		List<BaseCategoryView> baseCategoryViews = baseCategoryViewMapper.selectList(null);//null是无条件过滤
		//将baseCategoryViews列表中的所有BaseCategoryView对象，按照其category1Id（一级分类 ID）进行分组，得到一个Map
		Map<Long, List<BaseCategoryView>> BaseCategory1Map = baseCategoryViews.stream()		//转换成流
				.collect(	//收集流结果
						Collectors.groupingBy(		//分组收集器
								BaseCategoryView::getCategory1Id));	//根据一级id分类
		Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = BaseCategory1Map//按照一级分类的集合
															.entrySet() //获取map中所有键值对的集合
															.iterator();	//用该集合的迭代器遍历遍历所有键值对
		while (iterator.hasNext()){
			//获取entry对象
			Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
			//获取数据
			Long category1Id = entry.getKey();//一级分类id
			List<BaseCategoryView> categoryViewList = entry.getValue();//该一级分类下的所有记录（包含二级、三级信息）

			//创建一级分类的JSON对象，并设置基本信息
			JSONObject category1 = new JSONObject();
			category1.put("categoryName",categoryViewList.get(0).getCategory1Name());//因为一级分类名都一样，所以可以取第一条数据的名字
			category1.put("categoryId",category1Id);
			//获取一级分类下的二级分类数据
			Map<Long, List<BaseCategoryView>> baseCategory2Map = categoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
			Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = baseCategory2Map.entrySet().iterator();
			//	存储到二级分类数据：
			List<JSONObject> categoryChild2List = new ArrayList<>();
			while (iterator1.hasNext()){
				//获取二级分类的数据
				Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
				Long category2Id = entry1.getKey();
				//获取到二级分类id对应的集合数据
				List<BaseCategoryView> categoryViewList1 = entry1.getValue();
				JSONObject category2 = new JSONObject();
				category2.put("categoryName",categoryViewList1.get(0).getCategory2Name());
				category2.put("categoryId",category2Id);
				//	获取三级分类数据：直接循环遍历获取三级分类数据即可
				List<JSONObject> categoryChild3List = categoryViewList1.stream()
									.map(baseCategoryView -> {			//将流中的BaseCategoryView对象转换为JSONObject对象
					//	创建三级分类对象
					JSONObject category3 = new JSONObject();
					category3.put("categoryId", baseCategoryView.getCategory3Id());
					category3.put("categoryName", baseCategoryView.getCategory3Name());
					//	返回数据
					return category3;
				}).collect(Collectors.toList());	//将转换后的JSONObject对象收集为List
				//	获取三级分类数据添加到二级分类中;
				category2.put("categoryChild",categoryChild3List);
				categoryChild2List.add(category2);
			}

			//	将二级分类数据添加到一级分类中;
			category1.put("categoryChild",categoryChild2List);
			//	将所有一级分类对象添加到集合中
			list.add(category1);
		}
		return list;
	}

	@Override
	public List<BaseAttribute> findAttribute(Long category1Id) {
		//	调用mapper 层方法
		return baseAttributeMapper.selectAttribute(category1Id);
	}

	@TsCache(keyPrefix = "categoryView:")
	@Override
	public BaseCategoryView getBaseCategoryView(Long category3Id) {
		return baseCategoryViewMapper.selectById(category3Id);
	}

	/**
	 * 根据一级分类Id查询三级分类数据名称
	 * @param category1Id
	 * @return
	 */
	@Override
	public JSONObject getBaseCategoryList(Long category1Id) {
		//创建一个一级分类对象
		JSONObject category1 = new JSONObject();
		category1.put("category1Id",category1Id);
		//	根据业务分析通过一级分类Id查询视图比较方便;
		//	select * from base_category_view where category1_id = 1;
		List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(new LambdaQueryWrapper<BaseCategoryView>().eq(BaseCategoryView::getCategory1Id, category1Id));
		category1.put("categoryName",baseCategoryViewList.get(0).getCategory1Name());
		//获取二级分类
		Map<Long, List<BaseCategoryView>> baseCategory2Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
		Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = baseCategory2Map.entrySet().iterator();
		List<JSONObject> categoryChild2List = new ArrayList<>();
		while (iterator.hasNext()){
			Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
			JSONObject category2 = new JSONObject();
			category2.put("categoryId",entry.getKey());
			category2.put("categoryName",entry.getValue().get(0).getCategory2Name());
			//获取三级分类
			List<JSONObject> categoryChild3List = entry.getValue().stream().map(baseCategoryView -> {
				JSONObject category3 = new JSONObject();
				category3.put("categoryId", baseCategoryView.getCategory3Id());
				category3.put("categoryName", baseCategoryView.getCategory3Name());
				return category3;
			}).collect(Collectors.toList());
			category2.put("categoryChild",categoryChild3List);
			categoryChild2List.add(category2);
		}
		category1.put("categoryChild",categoryChild2List);
		return category1;
	}

	/**
	 * 根据一级分类Id查询三级分类数据集合
	 * @param category1Id
	 * @return
	 */
	@Override
	public List<BaseCategory3> findTopBaseCategory3(Long category1Id) {
		/*
			select * from base_category2 where category1_id = 1;
			select * from base_category3 where category2_id in (101,102,103) and is_top = 1 limit 7;
		 */
		//根据一级分类id查询二级分类信息
		List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(new LambdaQueryWrapper<BaseCategory2>().eq(BaseCategory2::getCategory1Id, category1Id));
		//获取二级分类信息中的二级id，以便后续查找三级分类信息使用
		List<Long> category2IdList = baseCategory2List.stream().map(BaseCategory2::getId).collect(Collectors.toList());
		//获取三级分类信息
		LambdaQueryWrapper<BaseCategory3> wrapper = new LambdaQueryWrapper<>();
		wrapper.in(BaseCategory3::getCategory2Id,category2IdList).eq(BaseCategory3::getIsTop,1).last(" limit 7 ");
		return baseCategory3Mapper.selectList(wrapper);
	}
}
